<template>
  <div class="membership-list">
    <div class="page-header">
      <h2>会员管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        开通会员
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="客户名称">
          <el-input
            v-model="filterForm.customer_name"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="会员等级">
          <el-select v-model="filterForm.level" placeholder="请选择" clearable style="width: 150px">
            <el-option label="普通会员" :value="1" />
            <el-option label="高级会员" :value="2" />
            <el-option label="VIP会员" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="会员状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="正常" :value="1" />
            <el-option label="冻结" :value="2" />
            <el-option label="已过期" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #409eff">
              <el-icon><UserFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总会员数</div>
              <div class="stat-value">{{ stats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon><CircleCheck /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">正常会员</div>
              <div class="stat-value">{{ stats.active }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon><Lock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">冻结会员</div>
              <div class="stat-value">{{ stats.frozen }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">即将过期</div>
              <div class="stat-value">{{ stats.expiring }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="membershipList" v-loading="loading" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column prop="level" label="会员等级" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.level === 1" type="info">普通会员</el-tag>
            <el-tag v-else-if="scope.row.level === 2" type="primary">高级会员</el-tag>
            <el-tag v-else-if="scope.row.level === 3" type="warning">VIP会员</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="会员状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="warning">冻结</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="danger">已过期</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="start_time" label="开通时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="到期时间" width="160">
          <template #default="scope">
            <span :class="{ 'text-danger': isExpiringSoon(scope.row.end_time) }">
              {{ formatDateTime(scope.row.end_time) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="会员费用" width="120">
          <template #default="scope">¥{{ scope.row.amount?.toFixed(2) || '0.00' }}</template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            <el-button type="success" size="small" @click="handleExtend(scope.row)">延期</el-button>
            <el-button
              v-if="scope.row.status === 1"
              type="warning"
              size="small"
              @click="handleFreeze(scope.row)"
            >
              冻结
            </el-button>
            <el-button
              v-else-if="scope.row.status === 2"
              type="success"
              size="small"
              @click="handleUnfreeze(scope.row)"
            >
              解冻
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Plus, UserFilled, CircleCheck, Lock, Clock } from '@element-plus/icons-vue'

  // 类型定义
  interface Membership {
    id: number
    customer_name: string
    level: number
    status: number
    start_time: number
    end_time: number
    amount: number
  }

  // 统计数据
  const stats = reactive({
    total: 0,
    active: 0,
    frozen: 0,
    expiring: 0,
  })

  // 筛选表单
  const filterForm = reactive({
    customer_name: '',
    level: null as number | null,
    status: null as number | null,
  })

  // 响应式数据
  const loading = ref(false)
  const membershipList = ref<Membership[]>([])

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0,
  })

  // 生命周期
  onMounted(() => {
    fetchMembershipList()
    fetchStats()
  })

  // 获取会员列表
  const fetchMembershipList = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        limit: pagination.pageSize,
      }

      if (filterForm.customer_name) params.customer_name = filterForm.customer_name
      if (filterForm.level) params.level = filterForm.level
      if (filterForm.status) params.status = filterForm.status

      const { membershipApi } = await import('@/api/customer/membership')
      const res = await membershipApi.getMembershipList(params)

      if (res.code === 0) {
        membershipList.value = res.data.list || []
        pagination.total = res.data.total || 0
      } else {
        ElMessage.error(res.msg || '获取会员列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取会员列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const { membershipApi } = await import('@/api/customer/membership')
      const res = await membershipApi.getMembershipStats()

      if (res.code === 0) {
        const statsData = res.data || {}
        stats.total = statsData.total || 0
        stats.active = statsData.active || 0
        stats.frozen = statsData.frozen || 0
        stats.expiring = statsData.expiring || 0
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchMembershipList()
    fetchStats()
  }

  // 重置
  const handleReset = () => {
    filterForm.customer_name = ''
    filterForm.level = null
    filterForm.status = null
    handleSearch()
  }

  // 新增
  const handleAdd = () => {
    ElMessage.info('开通会员功能开发中')
  }

  // 查看
  const handleView = (row: Membership) => {
    // 查看会员信息
    ElMessage.info('查看功能开发中')
  }

  // 延期
  const handleExtend = async (row: Membership) => {
    ElMessage.info('延期功能开发中')
  }

  // 冻结
  const handleFreeze = async (row: Membership) => {
    try {
      const { membershipApi } = await import('@/api/customer/membership')
      const res = await membershipApi.freezeMembership(row.id)

      if (res.code === 0) {
        ElMessage.success('冻结成功')
        fetchMembershipList()
        fetchStats()
      } else {
        ElMessage.error(res.msg || '冻结失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('冻结失败')
    }
  }

  // 解冻
  const handleUnfreeze = async (row: Membership) => {
    try {
      const { membershipApi } = await import('@/api/customer/membership')
      const res = await membershipApi.unfreezeMembership(row.id)

      if (res.code === 0) {
        ElMessage.success('解冻成功')
        fetchMembershipList()
        fetchStats()
      } else {
        ElMessage.error(res.msg || '解冻失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('解冻失败')
    }
  }

  // 删除
  const handleDelete = async (row: Membership) => {
    try {
      const { membershipApi } = await import('@/api/customer/membership')
      const res = await membershipApi.deleteMembership(row.id)

      if (res.code === 0) {
        ElMessage.success('删除成功')
        fetchMembershipList()
        fetchStats()
      } else {
        ElMessage.error(res.msg || '删除失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('删除失败')
    }
  }

  // 分页变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchMembershipList()
  }

  const handleCurrentChange = (page: number) => {
    pagination.page = page
    fetchMembershipList()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number) => {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return date.toLocaleString()
  }

  // 是否即将过期
  const isExpiringSoon = (endTime: number) => {
    if (!endTime) return false
    const now = Date.now() / 1000
    const diff = endTime - now
    return diff > 0 && diff < 7 * 24 * 60 * 60 // 7天内
  }
</script>

<style lang="scss" scoped>
  .membership-list {
    padding: 20px;

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .filter-card {
      margin-bottom: 20px;
    }

    .stats-row {
      margin-bottom: 20px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 15px;

        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 24px;
        }

        .stat-content {
          .stat-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
          }
        }
      }
    }

    .table-card {
      .text-danger {
        color: #f56c6c;
        font-weight: 500;
      }

      .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
